package cn.zz.veggie.application.service;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.zz.comm.core.types.IdNameObj;
import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.core.types.result.PageResult;
import cn.zz.comm.util.CollectorUtil;
import cn.zz.veggie.application.assembler.ShopAssembler;
import cn.zz.veggie.application.helper.ShopHelper;
import cn.zz.veggie.application.packer.ShopPacker;
import cn.zz.veggie.model.domain.Shop;
import cn.zz.veggie.model.query.ShopQuery;
import cn.zz.veggie.persistence.repository.ShopRepository;
import cn.zz.veggie.web.types.dto.mgmt.shop.MgmtShopQueryDto;
import cn.zz.veggie.web.types.dto.mgmt.shop.MgmtShopSaveDto;
import cn.zz.veggie.web.types.vo.mgmt.shop.MgmtShopVo;
import lombok.RequiredArgsConstructor;

/**
 * @author zhongq
 * @since 2024/7/26
 */
@Service
@RequiredArgsConstructor
public class ShopAppService {

	private final ShopRepository shopRepository;

	public List<IdNameObj> mgmtShopSearch(String keyword) {
		final ShopQuery shopQuery = ShopQuery.ofKeyword(keyword);
		final PageQuery pageQuery = PageQuery.all();
		final List<Shop> shops = shopRepository.findByPage(shopQuery, pageQuery);
		return CollectorUtil.bwl(shops, ShopPacker::toIdName);
	}

	public PageResult<MgmtShopVo> mgmtFindShops(MgmtShopQueryDto dto, PageQuery page) {
		ShopQuery shopQuery = ShopAssembler.buildQuery(dto);
		final List<Shop> shops = shopRepository.findByPage(shopQuery, page);
		return PageResult.of(page, CollectorUtil.bwl(shops, ShopPacker::toMgmtShopVo));
	}

	public void mgmtSaveShop(MgmtShopSaveDto dto) {
		Shop shop = ShopAssembler.buildSaveDomain(dto);
		shopRepository.save(shop);
	}

	public void mgmtRemoveShop(Integer id) {
		final Shop shop = shopRepository.findById(id);
		ShopHelper.requireValid(shop, id);
		shop.delete();
		shopRepository.save(shop);
	}
}